package com.example.foratm.example.idgenerator.second;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;

/**
 * @Description 日志随机数id生成类
 * @Author xutao
 * @Date 2022/9/20
 **/
public class RandomIdGenerator implements LogTraceIdGenerator {

    private static final Logger logger = LoggerFactory.getLogger(RandomIdGenerator.class);

    @Override
    public String generate() throws IdGenerationFailureException {
        String substrOfHostName = null;
        try {
            substrOfHostName = getLastFieldOfHostName();
        } catch (UnknownHostException e) {
            throw new IdGenerationFailureException("生成异常", e);
        }
        long currentTimeMillis = System.currentTimeMillis();
        String randomAlphameric = generateRandomAlphameric(8);
        return String.format("%s-%d-%s", substrOfHostName, currentTimeMillis, randomAlphameric);
    }

    private String getLastFieldOfHostName() throws UnknownHostException {
        String hostName = InetAddress.getLocalHost().getHostName();
        return getLastSubstrSplittedByDot(hostName);
    }


    protected String getLastSubstrSplittedByDot(String hostName) {
        if (null == hostName || hostName.isEmpty()) {
            throw new IllegalArgumentException("host name is empty");
        }
        String[] tokens = hostName.split("\\.");
        return tokens[tokens.length - 1];
    }


    /**
     * @param length 生成的随机字符串长度
     *               通过unicode 编码生成对应的字符 范围是 0～9 / a~z / A~Z
     * @return
     */
    protected String generateRandomAlphameric(int length) {
        if (length < 0) {
            throw new IllegalArgumentException("长度不能为空");
        }
        char[] randomChars = new char[length];
        int count = 0;
        while (count < length) {
            SecureRandom random = new SecureRandom();
            int randomAscii = random.nextInt(122);
            if (randomAscii >= 48 && randomAscii <= 57) {
                randomChars[count] = (char) ('0' + (randomAscii - 48));
                count++;
            } else if (randomAscii >= 65 && randomAscii <= 90) {
                randomChars[count] = (char) ('A' + (randomAscii - 65));
                count++;
            } else if (randomAscii >= 97 && randomAscii <= 122) {
                randomChars[count] = (char) ('a' + (randomAscii - 97));
                count++;
            }
        }
        return new String(randomChars);
    }


}
